package com.cy.jt.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/*登录成功后，返回给客户端一个json数据 */
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
       //可以在这样的方法中获取登录用户信息
        User principal = (User)authentication.getPrincipal();
        System.out.println(principal.getUsername()+"/"+principal.getPassword()+"/"+principal.getAuthorities());
       //获取用户凭证(默认为密码，credentials-表示凭证的意思)
        Object credentials = authentication.getCredentials();
        System.out.println("principal="+principal);
        System.out.println("credentials："+credentials);



        //设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉客户端响应数据的类型，以及客户端以怎样的编码显示
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //获取一个输出流对象
        PrintWriter out = httpServletResponse.getWriter();
        //向客户端输出一个json格式字符串
        /*
        //方法1：
        out.println("{\"state\":200,\"msg\":\"ok\"}");
        */
        //方法2：
        Map<String,Object> map = new HashMap<>();
        map.put("state","200");
        map.put("msg："+ principal.getUsername(),"登录成功");
        //基于jackson中的ObjectMapper对象将一个对象中的数据转换为json格式的数据
        String js = new ObjectMapper().writeValueAsString(map);

        out.println(js);
        out.flush();
    }
}
